package com.lindroy.androidplayer.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.ColorRes
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.view.children
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.navigation.NavHost
import androidx.navigation.findNavController
import com.elvishew.xlog.XLog
import com.google.android.material.appbar.AppBarLayout
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.logic.network.enums.LayoutState
import com.lindroy.androidplayer.ui.dialog.LoadingDialog
import com.lindroy.androidplayer.ui.widget.StatusBar
import com.lindroy.androidplayer.utils.getViewBinding
import com.lindroy.androidplayer.utils.no
import com.lindroy.androidplayer.utils.primaryColor
import com.lindroy.androidplayer.utils.yes
import com.lindroy.lib_utils.extensions.getResColor
import com.lindroy.lib_utils.extensions.setNewPadding
import com.lindroy.lib_utils.extensions.shortToast
import com.lindroy.lib_utils.extensions.statusbar.setStatusBarColor
import com.lindroy.lib_utils.extensions.statusbar.setStatusBarDarkMode
import com.lindroy.lib_utils.extensions.statusbar.setStatusBarLightMode
import com.lindroy.lib_utils.extensions.statusbar.statusBarHeight
import com.lindroy.multistatelayout.widget.FrameStateLayout

/**
 * @author Lin
 * @date 2022/1/8
 * @function 基类 Fragment
 */

typealias OnBackListener = (toolbar: Toolbar) -> Unit

abstract class BaseFragment<VB : ViewDataBinding> : Fragment() {

    open val isDarkModeStatusBar = true

    protected val TAG = this::class.simpleName

    protected lateinit var mBinding: VB
        private set

    protected lateinit var mActivity: AppCompatActivity
        private set

    val activityNavController by lazy { mActivity.findNavController(R.id.nav_main_act) }

    protected val stateLayout by lazy {
        if (mBinding.root is FrameStateLayout) {
            mBinding.root as FrameStateLayout
        } else {
            (mBinding.root as? ViewGroup)?.children?.firstOrNull { it is FrameStateLayout }
                ?.let { it as FrameStateLayout }
        }
    }

    private var isPause = true

    private val statusBar by lazy {
        mBinding.root.findViewById<StatusBar>(R.id.statusBar)
//        (mBinding.root as? ViewGroup)?.children?.firstOrNull { it is StatusBar }
//            ?.let { it as StatusBar }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = context as AppCompatActivity
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initData()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = getViewBinding(inflater, container)
        mBinding.lifecycleOwner = viewLifecycleOwner
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBinding.initView(savedInstanceState)
        initLoadingObserver()
        mBinding.initListener()
        initClick()
        registerToastListener()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        //从其他页面返回到 ViewPager 中的 Fragment 时，hidden 为 false 不一定可见，故需要增加 isPause 判断
//        XLog.tag(TAG).d("onHiddenChanged:$hidden")
        if (hidden || isPause) {
            return
        }
        setStatusBarMode()
    }

    override fun onResume() {
        super.onResume()
        isPause = false
        setStatusBarMode()
    }

    override fun onPause() {
        super.onPause()
        isPause = true
        XLog.tag(TAG).d("onPause")
    }

    private fun setStatusBarMode() {
        statusBar?.also {
            App.eventViewModel.postStatusBarDarkMode(it.isDarkMode)
        }
    }

    fun initToolbar(
        title: String = getString(R.string.app_name),
        isShowArrow: Boolean = true,
        @ColorRes toolBarColor: Int = R.color.color_primary,
        backListener: OnBackListener? = null
    ) {
        mBinding.root.findViewById<Toolbar>(R.id.toolbar).apply {
            this.title = title
            this.setBackgroundColor(ContextCompat.getColor(requireContext(), toolBarColor))
            mActivity.setSupportActionBar(this)
            mActivity.supportActionBar?.setDisplayHomeAsUpEnabled(isShowArrow)
            //ToolBar的属性设置要在setSupportActionBar方法之前调用
            this.setNavigationOnClickListener {
                if (backListener != null) {
                    backListener.invoke(this)
                } else {
                    //默认返回上一级
                    findNavController().navigateUp()
                }
            }
        }
    }

    fun initToolbar(
        @StringRes titleId: Int = R.string.app_name,
        isShowArrow: Boolean = true,
        @ColorRes toolBarColor: Int = R.color.color_primary,
        backListener: OnBackListener? = null
    ) = initToolbar(getString(titleId), isShowArrow, toolBarColor, backListener)

    fun registerLoadingDialogListener() {
        App.eventViewModel.loadingLiveData.observe(viewLifecycleOwner) { isShow ->
            XLog.tag("TTT").d("tag = ${TAG},isShow = $isShow")
            isShow.yes {
                LoadingDialog.show(this)
            }.no {
                LoadingDialog.dismiss(this)
            }
        }
    }

    private fun registerToastListener() {
        App.eventViewModel.toastLiveData.observe(viewLifecycleOwner) { msg ->
            msg?.also { shortToast(it) }
        }
    }

    private fun initLoadingObserver() {
        stateLayout?.apply {
            setOnViewsClickListener { state, view ->
                if (state == LayoutState.NOT_LOGIN) {
                    activityNavController.navigate(R.id.action_to_login)
                } else {
                    onRetryClick(view)
                }
            }
        }
    }

    private fun setLightModeStatusBar() {
        mActivity.setStatusBarColor(getResColor(R.color.colorWhite))
        mActivity.setStatusBarLightMode()
    }

    private fun setDarkModeStatusBar() {
        mActivity.setStatusBarColor(mActivity.primaryColor)
        mActivity.setStatusBarDarkMode()
    }

    abstract fun VB.initView(savedInstanceState: Bundle?)
    abstract fun initData()
    abstract fun VB.initListener()
    open fun initClick() {}
    open fun onRetryClick(view: View) {}

    override fun onDestroy() {
        super.onDestroy()
        if (this::mBinding.isLateinit) {
            mBinding.unbind()
        }
    }


}